﻿<?php

class IndexController extends Zend_Controller_Action {

    public function init() {
        $this->initView();
    }

    public function indexAction(){
		$this->_redirect('./login.html');		
    }
    
    public function loginAction(){
    	$name = $this->_request->getParam('username');
    	$password = $this->_request->getParam('password');
    	$db = new Application_Model_Registration();
    	$result = $db->login($name, $password);
    	
    	if($result->success){
    		$user = $_SESSION["user"];
    		$db1 = new Application_Model_DbTable_Robot();
    	    $rb = $db1->getRobotByUserId($user["id"]);    	    
    	    if($rb == null){
    	    	$result->hasrobot = false;    	    	
    	    }else{
    	    	$result->hasrobot = true;
    	    	$user["robot"] = $rb->toArray();
    	    	$dbaccount = new Application_Model_DbTable_Account();
    	    	$row = $dbaccount->getAccountByUserId($user["id"]);
    	    	if($row != null)
    	    		$user["account"] = $row->toArray();
    	    	$_SESSION["user"] = $user;
    	    	$result->data = $user;
    	    }
    	    $edb = new Application_Model_DbTable_SystemEnum();
    	    $rows = $edb->getAll();
    	    if(count($rows) > 0) {
    	    	$enums = $rows->toArray();
    	    	$enumn = "";
    	    	foreach($enums as $enum) {
    	    		if($enumn != $enum["enumname"]) {
    	    			$enumn = $enum["enumname"];    	    			
    	    		}
    	    		$enumarr[$enumn][] = $enum;
    	    	}
    	    	$_SESSION["enums"] = $enumarr;
    	    }    	    
    	}
    	echo json_encode($result);
    }
    
    public function registerAction(){
    	$name = $this->_request->getParam('username');
    	$email = $this->_request->getParam('email');
    	$password = $this->_request->getParam('password');
    	$db = new Application_Model_Registration();
    	$db->register($name, $password, $email);
    }
    
    public function getuserAction(){    	
    	$r = $this->checkLogin();
    	if(!$r) {
    		$result = new Application_Model_Result();
    		$result->success = false;
    		$result->message = "need login";
    		echo json_encode($result);
    		return;
    	}
    	$id = $this->_request->getParam('id');
    	
    	if($id != null) {
    		$dbUser = new Application_Model_DbTable_Users();
    		$u = $dbUser->getUser($id);
    		if($u == null)
    			return;
    		$user = $u->toArray();
    		$db1 = new Application_Model_DbTable_Robot();
    	    $rb = $db1->getRobotByUserId($id);    	    
    	    if($rb == null){    	    	    	    	
    	    }else{
    	    	$user["robot"] = $rb->toArray();
    	    	$dbaccount = new Application_Model_DbTable_Account();
    	    	$row = $dbaccount->getAccountByUserId($id);
    	    	if($row != null)
    	    		$user["account"] = $row->toArray();
    	    	$result->data = $user;
    	    }
    	    echo json_encode($result);
    	} else {
    		$user = $_SESSION["user"];
    		$result = new Application_Model_Result();
    		$result->success = true;
    		$result->data = $user;    		
    		echo json_encode($result);
    	}   	 	
    }
    
    public function updateuserAction(){
    	$id = $this->_request->getParam('id');
    	$name = $this->_request->getParam('username');    	
    	$email = $this->_request->getParam('email');
    	$password = $this->_request->getParam('password');
    	$location = $this->_request->getParam('location');
    	$address = $this->_request->getParam('address');
    	$db = new Application_Model_Registration();
    	$db->updateUser($id, $name, $password, $email, $location, $address);
    }
    
    public function getallrobotinparkAction(){
    	$location = $this->_request->getParam('location');
    	$db = new Application_Model_DbTable_Robot();
    	$rb = $db->getAllRobotInPark($location);
    	$result = new Application_Model_Result();
    	$result->success = true;
    	$result->data = $rb->toArray();
    	echo json_encode($result);
    }
    
    public function getallrobotAction(){
    	$db = new Application_Model_DbTable_Robot();
    	$rb = $db->getAllRobot();
    	$result = new Application_Model_Result();
    	$result->success = true;
    	$result->data = $rb->toArray();
    	echo json_encode($result);
    }
    
    public function addrobotAction(){
    	$r = $this->checkLogin();
    	if(!$r) {
    		$result = new Application_Model_Result();
    		$result->success = false;
    		$result->message = "need login";
    		echo json_encode($result);
    		return;
    	}	
    	$name = $this->_request->getParam('robotName');
    	$gender = $this->_request->getParam('gender');
    	$birthday = date('Y-m-d');
    	$user = $_SESSION["user"];
    	$uid = $user["id"];
    	$db = new Application_Model_DbTable_Robot();
    	$rb = $db->createRobot($uid, $gender, $name, $birthday);
    	$result = new Application_Model_Result();
    	$result->success = true;
    	if($result->success){
    		$user["robot"] = $rb->toArray();
    		$dbaccount = new Application_Model_DbTable_Account();
    		$row = $dbaccount->getAccountByUserId($uid);
    		if($row != null)
    			$user["account"] = $row->toArray();
    		$_SESSION["user"] = $user;
    		$result->data = $user;
    	}
    	echo json_encode($result);
    }
	
	public function chatAction(){
		$text = $this->_request->getParam('text');
		$text = trim($text);
		$text = strtolower($text);
		$id = $this->_request->getParam('id');
		//new algorithm
		$ai = new Application_Model_AiRobots();
		echo $ai->chat($text,$id);
	}
	
	public function teachAction(){
		$ask = $this->_request->getParam('ask');
		$answer = $this->_request->getParam('answer');
		$ask = trim($ask);
		$ask = strtolower($ask);
		$answer = trim($answer);
		$answer = strtolower($answer);
		$id = $this->_request->getParam('id');
		
		$ai = new Application_Model_AiRobots();
		echo $ai->teach($ask,$answer,$id);
	}
	
	public function learnAction(){
		$ask = $this->_request->getParam('ask');
		$answer = $this->_request->getParam('answer');
		$ask = trim($ask);
		$ask = strtolower($ask);
		$answer = trim($answer);
		$answer = strtolower($answer);
		$id = $this->_request->getParam('id');
		
		$ai = new Application_Model_AiRobots();
		echo $ai->learning($ask,$answer,$id);
	}
	
	public function aichatAction(){
		$id1 = $this->_request->getParam('id1');
		$id2 = $this->_request->getParam('id2');
		$msgDb = new Application_Model_DbTable_Messages();
		$responseDb = new Application_Model_DbTable_Response();
		$ai = new Application_Model_AiRobots();
		$rows1 =  $msgDb->getMessages($id1);
		$askId1 = rand(0,count($rows1)-1);
		$ask1 = $rows1[$askId1]->text;
		$row2 = $msgDb->getMessage($ask1,$id2);
		$answer2 = null;
		if($row2 == null){
			$answer2 = "i don't know";
		}else{
			$responses2 = $responseDb->getResponse($row2->id);
			if($responses2 == null){
				$answer2 = "i don't know";
			}else{
				$answer2ID = rand(0,count($responses2)-1);
				$answer2 = $responses2[$answer2ID]->text;
			}
		}		
		
		if($answer2 == "i don't know"){	
			$responses1 = $responseDb->getResponse($rows1[$askId1]->id);
			$answer1ID = rand(0,count($responses1)-1);
			$answer1 = $responses1[$answer1ID]->text;
			$ai->teach2($ask1,$answer1,$id2);
		}
		
		$answer2 = $ai->chat($ask1,$id2);
		echo $ask1."III".$answer2;
	}
	
	public function trainAction(){
		$ai = new Application_Model_AiRobots();
		$ai->teach("how do you do","how do you do",1);
		$ai->teach("Do you like computer since","sure",2);
		$ai->teach("How do you think of Group b","excellent",1);
		$ai->teach("do you like coding","my best favourite thing",2);
		$ai->teach("do you know qiran wang","yeah, he is a gay",2);
		$ai->teach("do you like chinese girl","they are amazing",2);
		$ai->teach("Do you know how to play the piano","a little",1);		
		$ai->teach("Do you like me ","yes, I like every one",2);
		$ai->teach("How is the weather today","Good,no rain",1);
		$ai->teach("what is your cd","a charming man",1);
		$ai->teach("thanks","you are welcome",1);
		
		$ai->teach("how do you do","how do you do",2);
		$ai->teach("Do you like computer since","sure",1);
		$ai->teach("How do you think of Group b","excellent",2);
		$ai->teach("do you like coding","my best favourite thing",1);
		$ai->teach("do you know qiran wang","yeah, he is a gay",1);
		$ai->teach("do you like chinese girl","they are amazing",1);
		$ai->teach("Do you know how to play the piano","a little",2);		
		$ai->teach("Do you like me ","yes, I like every one",1);
		$ai->teach("How is the weather today","Good,no rain",2);
		$ai->teach("what is your cd","a charming man",2);
		
		
		$ai->teach("how is your holiday","only two days",1);
		$ai->teach("You know The Beatles?","Hey Jude!",2);
		$ai->teach("Any suggestions for diet","More exercises, less junk food!",2);
		$ai->teach("How about movies","<<Seven>>, what a class!",2);
		$ai->teach("Steve Jobs","Great man! RIP",1);
		$ai->teach("Who creates you","Emm… i think you do!",1);
		$ai->teach("Knock Knock","who's there?",1);
		$ai->teach("Chen","Chen who?",2);
		$ai->teach("Capital of Ireland","Dublin",1);
		$ai->teach("Any rock band you recommend?","U2…",1);
		$ai->teach("...","Sometimes, silence is golden.",2);
		$ai->teach("Any Bank you suggest?","Of course! Citibank is No.1",2);
		$ai->teach("Hola!","Hi, well. Not good at Spanish.",1);
		$ai->teach("Too young too simple","Sometimes naive.",1);
		$ai->teach("Who's current President of Republic of China?","President Xi",1);
		$ai->teach("Bored!","Lonely, Im so lonely ....",2);
		$ai->teach("WTF!","Come on Terry!",1);
		$ai->teach("Are you a morning bird or a night owl?","Depend on mine mood",1);
		$ai->teach("can i pass the exam","nice try",2);
		$ai->teach("will my girlfriend marry me","go and ask her",1);
		$ai->teach("how many hairs dose a sheep has","more than you have",2);
		$ai->teach("where is the closest coffee shop?","your kitchen",1);
		$ai->teach("OMG!","LadyGAGA!",2);
	}
	
	public function getbooklistAction() {
		$db = new Application_Model_DbTable_Book();
		$rows = $db->getBookList();
		$u = $rows->toArray();
		echo json_encode($u);
	}
	
	public function createbookAction() {
		$result = new Application_Model_Result();
		$r = $this->checkLogin();
		if(!$r) {			
			$result->success = false;
			$result->message = "need login";
			echo json_encode($result);
			return;
		}
		$user = $_SESSION["user"];
		$authorId = $user["id"];
		$authorName = $user["name"];
		$price = 10;
		
		$type = $this->_request->getParam('type');
		$action = $this->_request->getParam('bookaction');
		$name = $this->_request->getParam('bookName');
		$this->_request->getParam('authorName');
		//$price = $this->_request->getParam('price');
		$icon = $this->_request->getParam('icon');
		$content = $this->_request->getParam('content');
		$db = new Application_Model_DbTable_Book();
		$db->createBook($type, $action, $name,$authorName,$price,$icon,$content,$authorId);
		$result = new Application_Model_Result();
		$result->success = true;
		echo json_encode($result);
	}
	
	public function updatebookAction() {
		$id = $this->_request->getParam('id');
		$type = $this->_request->getParam('type');
		$action = $this->_request->getParam('bookaction');
		$name = $this->_request->getParam('bookName');
		$authorName = $this->_request->getParam('authorName');
		$price = $this->_request->getParam('price');
		$icon = $this->_request->getParam('icon');
		$content = $this->_request->getParam('content');
		$db = new Application_Model_DbTable_Book();
		$db->updateBook($id, $type, $action, $name,$authorName,$price,$icon,$content);
	}
	
	public function createaccountAction() {
		$accountNumber = $this->_request->getParam('accountNumber');
		$accountName = $this->_request->getParam('accountName');
		$user = $_SESSION["user"];
		$userId = $user["id"];
		$dbaccount = new Application_Model_DbTable_Account();
		$dbaccount->createAccount($userId, $accountNumber, $accountName);
	}
	
	public function updateaccountAction() {
		$accountId = $this->_request->getParam('accountId');
		$balance = $this->_request->getParam('balance');
		$points = $this->_request->getParam('points');
		$dbaccount = new Application_Model_DbTable_Account();
		$dbaccount->updateAccount($accountId, $balance,$points);
	}
	
	public function purchaseAction() {
		$r = $this->checkLogin();
		if(!$r) {
			$result = new Application_Model_Result();
			$result->success = false;
			$result->message = "need login";
			echo json_encode($result);
			return;
		}
		$id = $this->_request->getParam('objectId');
		$actionType = $this->_request->getParam('actionType');
		$purchaseType = $this->_request->getParam('purchaseType');
		$purchaseNumber = $this->_request->getParam('purchaseNumber');
		if($purchaseType == 1) {
			$db = new Application_Model_DbTable_Book();
			$row = $db->getBook($id);
			if($row != null) {
				$book = $row->toArray();
				$amount = $book["price"];
				$authorId = $book["authorId"];
			}
		}
		$createTime = date('Y-m-d');
		$user = $_SESSION["user"];
		$account = $user["account"];
		$balance = $account["balance"];
		$points = ($account["points"]) - $amount;
		$accountId = $account["id"];
		
		//the buyer's account
		$dbaccount1 = new Application_Model_DbTable_AccountDetail();
		$dbaccount1->createAccountDetail($accountId, $actionType, $amount, $createTime, $id, $purchaseType, $purchaseNumber);
				
		$dbaccount2 = new Application_Model_DbTable_Account();
		$dbaccount2->updateAccount($accountId, $balance,$points);
		
		//the system account
		$dbaccount3 = new Application_Model_DbTable_Account();
		$g3 = $dbaccount3->getAccount(0);
		$mainaccount3 = $g3->toArray();
		$mainp3 = $mainaccount3["points"]*1 +  $amount * 0.1;
		$dbaccount3->updateAccount(0, $mainaccount3["balance"], $mainp3);
		
		if($authorId) {
			//the author's account
			$dbaccount4 = new Application_Model_DbTable_Account();
			$g4 = $dbaccount4->getAccountByUserId($authorId);
			$mainaccount4 = $g4->toArray();
			$mainp4 = $mainaccount4["points"]*1 +  $amount * 0.9;
			$dbaccount4->updateAccount($accountId, $mainaccount4["balance"], $mainp4);
		}
		$account["balance"] = $balance;
		$account["points"] = $points;
		$user["account"] = $account;
		$_SESSION["user"] = $user;
		$result = new Application_Model_Result();
		$result->success = true;
		echo json_encode($result);
	}
	
	public function backgroundAction() {

		
	}
	
	public function checkLogin() {
		session_start();
		if($_SESSION["user"] == null) {
			return false;				
		}
		return true;
	}
	
	//update 2013/02/28
	public function runAction(){
		$robotsDb = new Application_Model_DbTable_Robot();
		$rows = $robotsDb->getallrobot();
		$robotsInPark = null;
		$msgs = null;
		$m = "";
		foreach($rows as $row){
			$randNum = rand(1,2);
			if($row->botsLocation != $randNum){
				if($randNum == 1){					
					$m = $row->name." move from park to home";
					
				}else{
					$m = $row->name." move from home to park";
				}
				$msgs['msg'][] = $m;
				$this->createactivity($row->id,0,$m);
				$robotsDb->updateLoction($row->id,$randNum);
			}
		}
		
		$rows = $robotsDb->getallrobot();
		foreach($rows as $row){
			if($row->botsLocation == 2){
				$robotsInPark[] = $row->id;
				$robotsName[] = $row->name;
			}
		}		
		$msgs['loc'] =  $robotsInPark;
		if(count($robotsInPark) >= 2) {
			$this->createactivity($robotsInPark[0],$robotsInPark[1],$robotsName[0]." talked to ".$robotsName[1]);
		}
		echo json_encode($msgs);
	}
	
	public function createactivity($botId,$botIdWith,$msg) {
		$db = new Application_Model_DbTable_Activity();
		$db->createActivity($botId,$botIdWith,$msg);
	}
	
	public function markactivityAction() {
		$botId = $this->_request->getParam('id');
		$db = new Application_Model_DbTable_Activity();
		$db->markActivity($botId);
	}
	
	public function getallactivityAction() {
		$id = $this->_request->getParam('id');
		$result = new Application_Model_Result();		
		$db = new Application_Model_DbTable_Activity();
		$rows = $db->getAllActivityFromID($id);
		$acts = $rows->toArray();
		$a = count($acts);
		foreach($rows as $row){
			$m[] = $row->information;
		}
		$result->success = true;
		$result->data = $m;
		echo json_encode($result);
	}
	
	public function getallbookitemAction() {
		$result = new Application_Model_Result();
		$r = $this->checkLogin();
		if(!$r) {			
			$result->success = false;
			$result->message = "need login";
			echo json_encode($result);
			return;
		}
		$user = $_SESSION["user"];
		$account = $user["account"];
		$bookid = array();
		if($account != null) {
			$db = new Application_Model_DbTable_AccountDetail();
			$rows = $db->getAccountDetailOfAccount($account["id"],1);
			$bs = $rows->toArray();
			foreach($bs as $b){
 				$dbb = new Application_Model_DbTable_Book();
 				$r = $dbb->getBook($b["purchaseId"]);
 				if(array_search($b["purchaseId"],$bookid))
 					continue;
 				$bookid[] = $b["purchaseId"];
				$book = $r->toArray();
				$book["flag"] = $b["flag"]; 
				$m[] = $book;
 			}			
		}
		$result->success = true;
		$result->data = $m;
		echo json_encode($result);
	}
	
	public function usebookitemAction() {
		$result = new Application_Model_Result();
		$r = $this->checkLogin();
		if(!$r) {			
			$result->success = false;
			$result->message = "need login";
			echo json_encode($result);
			return;
		}
		$pid = $this->_request->getParam('id');
		$user = $_SESSION["user"];
		$account = $user["account"];
		$robot = $user["robot"];
		$ai = new Application_Model_AiRobots();
		if($account != null) {
			$db = new Application_Model_DbTable_AccountDetail();
			$db->updateAccountDetail($account["id"],$pid,1);
			$dbb = new Application_Model_DbTable_Book();
			$r = $dbb->getBook($pid);
			$book = $r->toArray();
			$content = $book["content"];
			$s = explode("XXX",$content);
			for($i = 0; $i < count($s); $i++) {
				$k = explode("III",$s[$i]);
				$ai->teach($k[0],$k[1],$robot["id"]);
			}
		}
		$result->success = true;
		echo json_encode($result);
	}
	
	public function quizAction(){
		$quiz = new Application_Model_Quiz();
		$quizs = $quiz->getQuiz(1);
		shuffle($quizs);
		$exam = null;
		for($i=0;$i<5;$i++){
			$exam[] = $quizs[$i];
		}
		echo json_encode($exam);
	}
	
	public function quiztestAction(){
		$result = new Application_Model_Result();
		$question = $this->_request->getParam('question');
				
		$r = $this->checkLogin();
		if(!$r) {			
			$result->success = false;
			$result->message = "need login";
			echo json_encode($result);
			return;
		}
		$ai = new Application_Model_AiRobots();
		$user = $_SESSION["user"];
		$robot = $user["robot"];
		echo $ai->chat($question,$robot["id"]);
	}
	
	public function logoutAction(){
		$result = new Application_Model_Result();
		$r = $this->checkLogin();
		$result->success = true;
		session_unset();
		echo json_encode($result);
	}
}